package com.playball.lottery.frm.buyhall;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ChildDTO;
import com.playball.lottery.customview.DelButtonAdapter;
import com.playball.lottery.customview.DelButtonAdapterJCZQBQC;
import com.playball.lottery.customview.MyDialog;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.frm.yhzx.BetProtocolActivity;
import com.playball.lottery.frm.yhzx.JddRechargeListActivity;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.Constants;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.JCUtil;
import com.playball.lottery.util.JCxhlbSortList;
import com.playball.lottery.util.JczqBQCUtil;
import com.playball.lottery.util.LotConstants;
import com.playball.lottery.util.MyPreference;


/**
 * 竞彩篮球选号列表
 * 
 * @author Administrator
 * 
 */
public class JcBasketballxhlbActivity extends BaseActivity implements DefConstants {
	/** 上下文内容 */
	private Context context;
	private TextView moneyText;
	private TextView tipText;
	private EditText et_beishu;
	private TextView btnBuy;
	private Button btnChioce;
	private View btnDelAll;
	/** 发起合买 */
	TextView buy_jcbasxhlb_btn_hemai;
	View buy_jczqxhlb_linearlayout01;
	View buy_jczqxhlb_linearlayout02;

	private String issueName;

	private int bs;// 倍数
	private long allMoney;// 总金额
	private long count; // 注数
	private String passType;
	private int buy_icon;

	private int len; // 全局变量长度

	private int currLen;// 未删除的剩余条数

	private ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

	boolean[] selected = new boolean[] { false, false, false, false, false, false, false };
	/** 竞彩蓝球胜分差过关方式 */
	boolean[] bfselected = new boolean[] { false, false, false, false };
	/** 篮球玩法 */
	private String strLQWF = "";
	/** 篮球玩法数字ID */
	private int playTypeID;
	/** 奖金预测 */
	private TextView tvMyuce;
	/** 最小奖金预测 */
	static BigDecimal bdminM = new BigDecimal("0");
	/** 最大奖金预测 */
	static BigDecimal bdmaxM = new BigDecimal("0");

	LinearLayout foot_layout;
	TextView tv_bet_protocol;
	CheckBox cb_bet_protocol;

	ListView listView;

	private String[] dyn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.context = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.buy_jcbsxhlb);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		// 获得传来的数组，并放入ListView
		Intent intent = getIntent();
		issueName = intent.getStringExtra("IssueName");
		strLQWF = intent.getStringExtra("strLQWF");// 篮球玩法

		// 初始化按钮
		initView();
		listView = (ListView) findViewById(R.id.lv_select_match);
		et_beishu = (EditText) findViewById(R.id.et_beishu);
		et_beishu.addTextChangedListener(textWatcher);
		// 标题
		titleBar();
		LayoutInflater inflater = LayoutInflater.from(this);
		foot_layout = (LinearLayout) inflater.inflate(R.layout.bet_protocol_foot, null);
		tv_bet_protocol = (TextView) foot_layout.findViewById(R.id.bet_protocol);
		cb_bet_protocol = (CheckBox) foot_layout.findViewById(R.id.bet_protocol_choice);
		listView.removeFooterView(foot_layout);
		listView.addFooterView(foot_layout);
		tv_bet_protocol.setText(Html.fromHtml("<u>我已阅读并同意《代购合买协议》"));
		cb_bet_protocol.setChecked(true);
		tv_bet_protocol.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivityForResult(new Intent(JcBasketballxhlbActivity.this, BetProtocolActivity.class), 0);
			}
		});
		@SuppressWarnings("unchecked")
		ArrayList<ChildDTO> arrayList = (ArrayList<ChildDTO>) intent.getSerializableExtra("list_jcdto");
		len = arrayList.size();
		// 处理intent获取的数据
		if (!strLQWF.equals("SFC")) {
			for (ChildDTO child : arrayList) {
				String jc_mid = child.getmId();
				String str_hteam = child.gethTeam();
				String str_vteam = child.getvTeam();
				String str_sp = child.getStr_sp();
				list = getData(jc_mid, str_hteam, str_vteam, str_sp, child.geteTime());
			}
		} else {// 胜分差
			for (ChildDTO child : arrayList) {
				String jc_mid = child.getmId();
				String str_hteam = child.gethTeam();
				String str_vteam = child.getvTeam();
				String str_content = "";
				List<String> selspslist = new ArrayList<String>();
				// 转化list为string
				String str1;
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < child.getList_sfcsgridview_selectconcent().size(); i++) {
					sb.append(child.getList_sfcsgridview_selectconcent().get(i) + ","); // ,
				}
				for (int i = 0; i < child.getList_sfcfgridview_selectconcent().size(); i++) {
					sb.append(child.getList_sfcfgridview_selectconcent().get(i) + ","); // ,
				}
				str1 = sb.toString();
				str_content = str1;
				List<String> selSFCspslist = new ArrayList<String>();
				selSFCspslist = child.getList_sfcsgridview_selectsp();
				List<String> selSFCspflist = new ArrayList<String>();
				selSFCspflist = child.getList_sfcfgridview_selectsp();
				selspslist = new ArrayList<String>(selSFCspslist);
				selspslist.addAll(selSFCspflist);
				list = getSFCData(jc_mid, str_hteam, str_vteam, str_content, selspslist, child.geteTime());
			}
		}
		// //对选择的赛事进行排序,jc_mid
		ArrayList<HashMap<String, Object>> newlist = new ArrayList<HashMap<String, Object>>();
		newlist = JCxhlbSortList.SortListData(list);
		initBaseAdapter(newlist);

		/************************* 2014年6月17日14:25:48 *******************************************/
		// 设置 默认 sf dxf (8串1) sfc(4串1)
		String[] arrs = null;
		if (!strLQWF.equals("SFC")) {
			arrs = context.getResources().getStringArray(R.array.buy_jc);
		} else {
			arrs = context.getResources().getStringArray(R.array.buy_jczq_bf);
		}
		int length;
		length = ApplicationData.getInstance().getList_jcdto().size();
		// 最多只有8串1
		if (length > 7) {
			length = 8;
		}
		// 如果是胜分差，最多只有4串1
		if (strLQWF.equals("SFC")) {
			if (length > 3) {
				length = 4;
			}
			String pass[] = new String[length - 1];
			for (int i = 0; i < length - 1; i++) {
				pass[i] = arrs[i];
			}

			if (length == 1) {
				bfselected[0] = true;
			} else if (length == 2) {
				bfselected[1] = true;
			} else if (length == 3) {
				bfselected[2] = true;
			} else if (length == 4) {
				bfselected[3] = true;
			} else {
				bfselected[3] = true;
			}
			String selectedStr = "";
			for (int i = 0; i < bfselected.length; i++) {
				if (bfselected[i] == true) {
					if (selectedStr.equals("")) {
						selectedStr = getResources().getStringArray(R.array.buy_jczq_bf)[i];
					} else {
						selectedStr = selectedStr + "," + getResources().getStringArray(R.array.buy_jczq_bf)[i];
					}
				}
			}
			passType = selectedStr.replace("串", "*");
			btnChioce.setText(selectedStr);
			allMoney = getMoney(ApplicationData.getInstance().getList_jcdto());

		}
		// sf dxf (8串1)
		else {
			String pass[] = new String[length - 1];
			for (int i = 0; i < length - 1; i++) {
				pass[i] = arrs[i];
			}

			if (length == 2) {
				selected[0] = true;
			} else if (length == 3) {
				selected[1] = true;
			} else if (length == 4) {
				selected[2] = true;
			} else if (length == 5) {
				selected[3] = true;
			} else if (length == 6) {
				selected[4] = true;
			} else if (length == 7) {
				selected[5] = true;
			} else if (length == 8) {
				selected[6] = true;
			} else {
				selected[6] = true;
			}

			String selectedStr = "";
			for (int i = 0; i < selected.length; i++) {
				if (selected[i] == true) {
					if (selectedStr.equals("")) {
						selectedStr = getResources().getStringArray(R.array.buy_jc)[i];
					} else {
						selectedStr = selectedStr + "," + getResources().getStringArray(R.array.buy_jc)[i];
					}
				}
			}
			passType = selectedStr.replace("串", "*");
			btnChioce.setText(selectedStr);
			allMoney = getMoney(ApplicationData.getInstance().getList_jcdto());
		}

		View.OnClickListener listener = new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				passType = "";
				Dialog dialog = null;
				String[] arrs = null;
				if (!strLQWF.equals("SFC")) {
					arrs = context.getResources().getStringArray(R.array.buy_jc);
				} else {
					arrs = context.getResources().getStringArray(R.array.buy_jczq_bf);
				}
				int length;
				length = ApplicationData.getInstance().getList_jcdto().size();
				// 最多只有8串1
				if (length > 7) {
					length = 8;
				}
				// 如果是胜分差，最多只有4串1
				if (strLQWF.equals("SFC")) {
					if (length > 3) {
						length = 4;
					}
				}
				if (!strLQWF.equals("SFC")) {
					if (length < 2) {
						Toast.makeText(JcBasketballxhlbActivity.this, R.string.select_at_least_two, Toast.LENGTH_SHORT)
								.show();
					} else {
						String pass[] = new String[length - 1];
						for (int i = 0; i < length - 1; i++) {
							pass[i] = arrs[i];
						}
						Builder builder = new AlertDialog.Builder(JcBasketballxhlbActivity.this);
						builder.setTitle(getString(R.string.buy_jclist_passtype));
						builder.setCancelable(false);
						DialogInterface.OnMultiChoiceClickListener mutiListener = new DialogInterface.OnMultiChoiceClickListener() {

							@Override
							public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
								selected[which] = isChecked;
							}
						};

						builder.setMultiChoiceItems(pass, selected, mutiListener);
						DialogInterface.OnClickListener btnListener = new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int which) {
								String selectedStr = "";
								for (int i = 0; i < selected.length; i++) {
									if (selected[i] == true) {
										if (selectedStr.equals("")) {
											selectedStr = getResources().getStringArray(R.array.buy_jc)[i];
										} else {
											selectedStr = selectedStr + ","
													+ getResources().getStringArray(R.array.buy_jc)[i];
										}
									}
								}
								passType = selectedStr.replace("串", "*");
								btnChioce.setText(selectedStr);
								allMoney = getMoney(ApplicationData.getInstance().getList_jcdto());
							}
						};
						builder.setPositiveButton("确定", btnListener);
						dialog = builder.create();
						dialog.show();
					}
				} else {
					if (length < 1) {
						Toast.makeText(JcBasketballxhlbActivity.this, R.string.select_at_least_one, Toast.LENGTH_SHORT)
								.show();
					} else {
						String pass[] = new String[length];
						for (int i = 0; i < length; i++) {
							pass[i] = arrs[i];
						}
						Builder builder = new AlertDialog.Builder(JcBasketballxhlbActivity.this);
						builder.setTitle(getString(R.string.buy_jclist_passtype));
						builder.setCancelable(false);
						DialogInterface.OnMultiChoiceClickListener mutiListener = new DialogInterface.OnMultiChoiceClickListener() {

							@Override
							public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
								bfselected[which] = isChecked;
							}
						};
						builder.setMultiChoiceItems(pass, bfselected, mutiListener);
						DialogInterface.OnClickListener btnListener = new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int which) {
								String selectedStr = "";
								for (int i = 0; i < bfselected.length; i++) {
									if (bfselected[i] == true) {
										if (selectedStr.equals("")) {
											selectedStr = getResources().getStringArray(R.array.buy_jczq_bf)[i];
										} else {
											selectedStr = selectedStr + ","
													+ getResources().getStringArray(R.array.buy_jczq_bf)[i];
										}
									}
								}
								passType = selectedStr.replace("串", "*");
								btnChioce.setText(selectedStr);
								allMoney = getMoney(ApplicationData.getInstance().getList_jcdto());
							}
						};
						builder.setPositiveButton("确定", btnListener);
						dialog = builder.create();
						dialog.show();
					}
				}
			}
		};
		btnChioce.setOnClickListener(listener);

		// 购买按钮
		btnBuy.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if(bs * allMoney > 2000000){
					Toast.makeText(context, "单个方案的总金额必须在2彩豆至2000000彩豆之间", Toast.LENGTH_SHORT).show();
					return;
				}
				if (list.size() < 1) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.betting_accounts_cannot_be_empty,
							Toast.LENGTH_SHORT).show();
				} else if (passType == null || passType.equals("")) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.select_a_pass_way, Toast.LENGTH_SHORT)
							.show();
				} else if (et_beishu.getText().toString().equals("")) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.buy_at_least_one_times, Toast.LENGTH_SHORT)
							.show();
					et_beishu.setText("1");
					// beishu.setText("1");
				} else {

					if (cb_bet_protocol.isChecked() == false) {
						Toast.makeText(JcBasketballxhlbActivity.this,
								R.string.need_to_agree_to_just_can_continue_to_buy, Toast.LENGTH_SHORT).show();
						return;
					}
					startBuyThread();
					/*
					 * MyDialog dialog = new
					 * MyDialog.Builder(JcBasketballxhlbActivity
					 * .this).setTitle("购买提示").setMessage("是否确认购买？")
					 * .setPositiveButton("确定", new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialog, int which) {
					 * startBuyThread(); dialog.cancel(); }
					 * }).setNegativeButton("取消", new
					 * DialogInterface.OnClickListener() {
					 * 
					 * @Override public void onClick(DialogInterface dialog, int
					 * which) { dialog.cancel(); } }).create();
					 * dialog.setCanceledOnTouchOutside(false);
					 * dialog.setCancelable(true);// 设置back键是否可以取消
					 * dialog.show();
					 */
				}
			}
		});

		btnDelAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ApplicationData.getInstance().getList_jcdto().size() > 0) {
					MyDialog.Builder dialog = new MyDialog.Builder(JcBasketballxhlbActivity.this);
					dialog.setTitle("清空号码提示");
					dialog.setMessage("清空后您已选择的号码列表将会清空，确认继续?");
					dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							et_beishu.setText("1");
							moneyText.setText("共0彩豆");
							tvMyuce.setText("0");
							btnChioce.setText("请选择过关方式");
							allMoney = 0;
							bs = 1;
							// 获得自定义的应用程序BallDTO,初始化
							ApplicationData.getInstance().resetJCData();
							list = new ArrayList<HashMap<String, Object>>();
							buy_jczqxhlb_linearlayout01.setVisibility(View.GONE);
							buy_jczqxhlb_linearlayout02.setVisibility(View.VISIBLE);
							tipText.setText("共--场比赛，截止时间：------------");
							currLen = 0;
							// 当用户选择清空时，初始化奖金预测值
							bdminM = new BigDecimal("0");
							bdmaxM = new BigDecimal("0");
							dialog.cancel();
						}
					});
					dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					}).create().show();
				}
			}
		});

		// 发起合买
		buy_jcbasxhlb_btn_hemai.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				if (list.size() < 1) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.betting_accounts_cannot_be_empty,
							Toast.LENGTH_SHORT).show();
				} else if (passType == null || passType.equals("")) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.select_a_pass_way, Toast.LENGTH_SHORT)
							.show();
				} else if (et_beishu.getText().toString().equals("")
						|| Long.parseLong(et_beishu.getText().toString()) == 0) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.betting_accounts_cannot_be_empty,
							Toast.LENGTH_SHORT).show();
					et_beishu.setText("1");
				} else {
					if (strLQWF.equals("RFSF")) {
						playTypeID = 9101;
					} else if (strLQWF.equals("SF")) {
						playTypeID = 9102;
					} else if (strLQWF.equals("SFC")) {
						playTypeID = 9103;
					} else if (strLQWF.equals("DXF")) {
						playTypeID = 9104;
					}
					try {

						if (cb_bet_protocol.isChecked() == false) {
							Toast.makeText(JcBasketballxhlbActivity.this,
									R.string.need_to_agree_to_just_can_continue_to_buy, Toast.LENGTH_SHORT).show();
							return;
						}

						Intent intent = new Intent();
						if (moneyText.getText().toString() != null) {
							intent.putExtra("AllMoney", Integer.parseInt(allMoney + ""));
						} else {
							intent.putExtra("AllMoney", 0);
						}
						intent.putExtra("bs", bs);
						intent.putExtra("LotID", LOT_ID_JCLQ);
						intent.putExtra("IssueName", issueName);
						intent.putExtra("IssueID", "2016");
						intent.putExtra("strLQWF", strLQWF);
						intent.putExtra("passType", passType);
						intent.putExtra("PlayTypeId", playTypeID);
						JSONObject params0 = new JSONObject();
						params0.put("playid", playTypeID);
						params0.put("number", getLotNum(ApplicationData.getInstance().getList_jcdto()));

						intent.putExtra("Number", "[" + params0.toString() + "]");
						intent.setClass(JcBasketballxhlbActivity.this, FaQiHeMaiActivity.class);
						JcBasketballxhlbActivity.this.startActivityForResult(intent, REQ_CODE_BUYMAIN);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						// e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						// e.printStackTrace();
					}
				}
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private TextWatcher textWatcher = new TextWatcher() {
		private boolean isChanged = false;

		public void afterTextChanged(Editable s) {
			if (isChanged) {
				return;
			}
			// TODO Auto-generated method stub
			if (!et_beishu.getText().toString().equals("")) {

				bs = Integer.parseInt(s.toString());
				isChanged = true;
				String str2 = s.toString().trim().replaceFirst("^0*", "");// 正则去除
				if (bs < 1) {
					Toast.makeText(JcBasketballxhlbActivity.this, R.string.the_minimum_ratio_of_one, Toast.LENGTH_SHORT)
							.show();
					et_beishu.setText("1");
					bs = 1;
				} else if (bs > 99999) {
					Toast.makeText(JcBasketballxhlbActivity.this,
							R.string.the_maximum_ratio_of_nine_hundred_and_ninety_nine, Toast.LENGTH_SHORT).show();
					et_beishu.setText("99999");
					bs = 99999;
				} else {
					et_beishu.setText(str2);
				}
				et_beishu.setSelection(et_beishu.length());
				isChanged = false;
				et_beishu.invalidate();

				Long m = Long.parseLong(allMoney + "") * Integer.parseInt(et_beishu.getText().toString());
				moneyText.setText("共" + m + "彩豆");
				// 保留小数点后2位,
				BigDecimal bdbs = new BigDecimal(bs + "");
				String f1 = bdbs.multiply(bdminM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
				String f2 = bdbs.multiply(bdmaxM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
				tvMyuce.setText(f1 + "彩豆-" + f2 + "彩豆");
			} else {
				et_beishu.setOnFocusChangeListener(new OnFocusChangeListener() {
					public void onFocusChange(View view, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							et_beishu.setText("");
						} else {
							if (et_beishu.getText().toString().equals("")) {
								Toast.makeText(JcBasketballxhlbActivity.this, R.string.buy_at_least_one_times,
										Toast.LENGTH_SHORT).show();
							}
						}
					}
				});
				// et_beishu.setText("0");
				bs = 0;
				moneyText.setText("共0彩豆");
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

	};

	class AsyncLoader extends AsyncTask<String, Integer, String> {// 继承AsyncTask

		String action;
		ShowTipDialog showdialog = new ShowTipDialog();

		// 1.准备运行
		protected void onPreExecute() {
			showdialog.showDialog(JcBasketballxhlbActivity.this);
		}

		// 2.正在后台运行
		@Override
		protected String doInBackground(String... paramsArr) {
			// 处理后台执行的任务，在后台线程执行
			String strResult = null;

			action = paramsArr[1];
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(paramsArr[0], UserID, action, getApplicationContext());
			// 获取请求返回值
			return strResult;
		}

		// 3.进度更新
		protected void onProgressUpdate(Integer... progress) {
		}

		// 4.完成后台任务
		protected void onPostExecute(String result) {
			if (result != null) {
				if (action.equals("207")) {
					Buy(result);
				}
				showdialog.closeDialog();
			} else {
				Toast.makeText(JcBasketballxhlbActivity.this, getString(R.string.problem_01), Toast.LENGTH_LONG).show();
			}
		}

		// 5.完成后操作
		protected void onCancelled() {
		}

	}

	private void startBuyThread() {
		ArrayList<ChildDTO> arrayList = ApplicationData.getInstance().getList_jcdto();
		String lotNum = getLotNum(arrayList);

		AsyncLoader task = new AsyncLoader();
		dyn = new String[2];
		JSONObject params = new JSONObject();

		try {
			if (strLQWF.equals("RFSF")) {
				playTypeID = 9101;
			} else if (strLQWF.equals("SF")) {
				playTypeID = 9102;
			} else if (strLQWF.equals("SFC")) {
				playTypeID = 9103;
			} else if (strLQWF.equals("DXF")) {
				playTypeID = 9104;
			}
			// 设置请求所需参数
			JSONObject params0 = new JSONObject();
			params0.put("playid", playTypeID);
			params0.put("number", lotNum);
			params.put("SchemeType", 1);// 方案类型 1自购，2合买，3保存 1
			params.put("BetType", 1);// 投注类型 1选号投注 2单式上传 3先发后传 1
			params.put("BonusScale", 0);
			params.put("AssureShare", 0);
			params.put("Description", "");
			params.put("OpenUserList", "");
			params.put("SecrecyLevel", 4);
			params.put("BuyShare", bs * allMoney);
			params.put("Multiple", bs);
			params.put("LotteryID", LotConstants.LOT_ID_JCLQ);
			params.put("IssueName", issueName);// issueName
			params.put("IssueID", 2016);
			params.put("Number", "[" + params0.toString() + "]");
			params.put("Money", bs * allMoney);
		} catch (JSONException ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		dyn[0] = params.toString();
		dyn[1] = "207";
		task.execute(dyn);
	}

	public void Buy(String strResult) {
		try {
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			if (Integer.parseInt(js.getString("Code")) < 0) {
//				buy_icon = R.drawable.buy_failure;
//				if(js.getString("Data").contains(Constants.BALANCE_BUZU)){
//					Intent intent = new Intent();
//					intent.setClass(context, JddRechargeListActivity.class);
//					intent.putExtra("params", dyn[0]);
//					startActivityForResult(intent, REQ_CODE_NO_MONEY_2_RECHARGE);
//				} else {
					new ShowTipDialog().showBuyInfo(JcBasketballxhlbActivity.this, js.getString("Data"), "购买失败", buy_icon,
							dyn[0]);
//				}
				
			} else {
				buy_icon = R.drawable.buy_success;
				String msg = "发起竞彩篮球购买方案\n\n我的认购：" + (bs * allMoney/*
																					 * -
																					 * canDeductMoney
																					 */)/* + "彩豆\n账户余额："
						+ ConvertJsonToList.getMap(js.getString("Data")).get("Balance").toString()/*
																								 * getBalance
																								 * (
																								 * )
																								 */+ "彩豆"+"\n方案编号："+js.getString("Data").toString();

				new ShowTipDialog().showBuyInfo(JcBasketballxhlbActivity.this, msg, "投注成功", buy_icon, dyn[0]);

				// 存贮数据
				MyPreference.getInstance(this).storeBLotID(LotConstants.LOT_ID_JCZQ);
			}
		} catch (JSONException ex) {
			// 异常处理代码
			Log.e("error", ex.toString());
		}
	}

	public String getBalance() {
		String money = "";
		String strResult = null;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 设置请求所需参数
			JSONObject params = new JSONObject();
			// 设置请求action
			String action = "107";// 108获取用户基本信息
			// 获取请求返回值
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(params.toString(), UserID, action,
					getApplicationContext());
			JSONTokener jsonParser = new JSONTokener(strResult);
			JSONObject js = (JSONObject) jsonParser.nextValue();
			map = ConvertJsonToList.getMap(js.getString("Data"));
			money = map.get("Balance").toString();
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			Log.e("error", ex.toString());
		}
		return money;
	}

	// 拼接投注号码
	public String getLotNum(List<ChildDTO> arrayList) {
		String lotNum = "";
		for (ChildDTO jcdto : arrayList) {
			lotNum += jcdto.getmId() + "=";
			if (!strLQWF.equals("SFC")) {
				// i作为一场比赛中选胜平负的个数
				String info = "";
				String sp = JCUtil.zhuanHuanSPGeShi(jcdto.getStr_sp());
				if (strLQWF.equals("DXF")) {
					if (sp.contains("3")) {
						info += "2/";
					}
					if (sp.contains("0")) {
						info += "1/";
					}
				} else {
					if (sp.contains("3")) {
						info += "1/";
					}
					if (sp.contains("0")) {
						info += "2/";
					}
				}
				info = info.substring(0, info.length() - 1);
				lotNum = lotNum + info + ",";
			} else {
				String info = "";
				String touzhuNum = jcdto.getBtnsfcAllcontent();
				// 转为服务器要求的投注格式
				touzhuNum = touzhuNum.replaceAll("主胜1-5", "01");
				touzhuNum = touzhuNum.replaceAll("主胜6-10", "02");
				touzhuNum = touzhuNum.replaceAll("主胜11-15", "03");
				touzhuNum = touzhuNum.replaceAll("主胜16-20", "04");
				touzhuNum = touzhuNum.replaceAll("主胜21-25", "05");
				touzhuNum = touzhuNum.replaceAll("主胜26\\+", "06");
				touzhuNum = touzhuNum.replaceAll("客胜1-5", "11");
				touzhuNum = touzhuNum.replaceAll("客胜6-10", "12");
				touzhuNum = touzhuNum.replaceAll("客胜11-15", "13");
				touzhuNum = touzhuNum.replaceAll("客胜16-20", "14");
				touzhuNum = touzhuNum.replaceAll("客胜21-25", "15");
				touzhuNum = touzhuNum.replaceAll("客胜26\\+", "16");
				info = touzhuNum.replaceAll(",", "/");
				if (info.endsWith("/")) {
					info = info.substring(0, info.length() - 1);
				}
				lotNum = lotNum + info + ",";
			}

		}
		lotNum = lotNum.substring(0, lotNum.length() - 1);
		if (passType.contains("单关")) {
			passType = passType.replaceAll("单关", "1*1");
		}
		lotNum = lotNum + "|" + passType + "|0";// |0定胆数0
		return lotNum;
	}

	/**
	 * 初始化奖金预测值
	 */
	public static void initMoney() {
		bdminM = new BigDecimal("0");
		bdmaxM = new BigDecimal("0");
	}

	// 获取金额
	public long getMoney(List<ChildDTO> arrayList) {
		// 当用户重新选择几串一时，初始化值
		bdminM = new BigDecimal("0");
		bdmaxM = new BigDecimal("0");
		count = 0;
		String[] types = passType.split(",");
		boolean isFirst = true;
		for (int i = 0; i < types.length; i++) {
			String type = types[i];
			// 进行计算所需的参数
			int num = getNumByPassType(type);
			if (num != 0) {
				String result = "";
				if (!strLQWF.equals("SFC")) {
					result = JCUtil.getMatchCount(num, arrayList);
				} else {
					result = JczqBQCUtil.getMatchCount(num, arrayList);
				}
				count += Long.parseLong(result.split("\\|")[0]);
				// 最小奖金
				BigDecimal bdTWO = new BigDecimal("2");
				BigDecimal bdmintemp = new BigDecimal(result.split("\\|")[1]);
				BigDecimal bdtemp = bdTWO.multiply(bdmintemp);
				if (isFirst) {
					BigDecimal bdmin0 = new BigDecimal(result.split("\\|")[1]);
					bdminM = bdTWO.multiply(bdmin0);
					isFirst = false;
				}
				if (bdtemp.compareTo(bdminM) == -1 || bdtemp.compareTo(bdminM) == 0) {
					bdminM = bdtemp;
				}
				// 最大奖金
				BigDecimal bdmax0 = new BigDecimal(result.split("\\|")[2]);
				bdmaxM = bdmaxM.add(bdTWO.multiply(bdmax0));
			}
		}
		moneyText.setText("共" + (Long.parseLong((count * 2) * bs + "") + "") + "彩豆");
		// 保留小数点后2位,
		BigDecimal bdbs = new BigDecimal(bs + "");
		String f1 = bdbs.multiply(bdminM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
		String f2 = bdbs.multiply(bdmaxM).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
		tvMyuce.setText(f1 + "彩豆-" + f2 + "彩豆");
		return count * 2;
	}

	// 根据过关方式获取计算阶乘时所需参数
	public int getNumByPassType(String type) {
		int num = 0;
		if (type.equals("单关")) {
			num = 1;
		}
		if (type.equals("2*1")) {
			num = 2;
		}
		if (type.equals("3*1")) {
			num = 3;
		}
		if (type.equals("4*1")) {
			num = 4;
		}
		if (type.equals("5*1")) {
			num = 5;
		}
		if (type.equals("6*1")) {
			num = 6;
		}
		if (type.equals("7*1")) {
			num = 7;
		}
		if (type.equals("8*1")) {
			num = 8;
		}
		return num;
	}

	// 初始化
	public void initView() {
		initText();

		buy_jczqxhlb_linearlayout01 = findViewById(R.id.buy_jczqxhlb_linearlayout01);
		buy_jczqxhlb_linearlayout02 = findViewById(R.id.buy_jczqxhlb_linearlayout02);
		btnBuy = (TextView) findViewById(R.id.bottom_right_btn);
		btnChioce = (Button) findViewById(R.id.btn_playmethod);
		btnDelAll = findViewById(R.id.view_clear);
		buy_jcbasxhlb_btn_hemai = (TextView) findViewById(R.id.bottom_left_btn);
	}

	// 初始化TextView
	public void initText() {
		et_beishu = (EditText) findViewById(R.id.et_beishu);
		moneyText = (TextView) findViewById(R.id.bottom_tv_money);
		tipText = (TextView) findViewById(R.id.tv_tips_endtime);
		tvMyuce = (TextView) findViewById(R.id.tv_win_ranger);

		bs = 1;
		et_beishu.setText("1");
		moneyText.setText("共0彩豆");

	}

	// 获取页面显示list
	private ArrayList<HashMap<String, Object>> getData(String jc_mid, String str_hteam, String str_vteam, String jc_sp,
			String str_time) {
		// 拿到新的号码放到List
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("buy_jcxhlb_list_mid", jc_mid);
		map.put("buy_jcxhlb_list_hteam", str_hteam);
		map.put("buy_jcxhlb_list_vteam", str_vteam);
		map.put("buy_jcxhlb_list_sp", jc_sp);
		map.put("buy_jcxhlb_list_delete", R.drawable.default_delbtn02);
		map.put("tip_time", str_time);
		map.put("list_strLQWF", strLQWF);
		list.add(map);
		return list;
	}

	/**
	 * 获取页面显示list,胜分差使用
	 * 
	 * @param jc_mid
	 *            赛事号
	 * @param str_hteam
	 *            主队
	 * @param str_vteam
	 *            客队
	 * @param jc_sp
	 *            sp
	 * @param selspslist
	 *            选择sp list
	 * @param str_time
	 *            截止时间
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> getSFCData(String jc_mid, String str_hteam, String str_vteam,
			String jc_sp, List<String> selspslist, String str_time) {
		// 拿到新的号码放到List
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("buy_jcxhlb_list_mid", jc_mid);
		map.put("buy_jcxhlb_list_hteam", str_hteam);
		map.put("buy_jcxhlb_list_vteam", str_vteam);
		map.put("buy_jcxhlb_list_touzhu", jc_sp);
		// list转化为string
		String str1;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < selspslist.size(); i++) {
			if (!selspslist.get(i).equals("0")) {
				sb.append(selspslist.get(i) + ","); // ,
			}
		}
		str1 = sb.toString();
		map.put("buy_jcxhlb_list_sp", str1);
		map.put("buy_jcxhlb_list_delete", R.drawable.default_delbtn02);
		map.put("tip_time", str_time);
		list.add(map);
		return list;
	}

	// 初始化适配器
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void initBaseAdapter(ArrayList list) {
		DelButtonAdapter listAdapter = null;
		DelButtonAdapterJCZQBQC listAdapterBQC = null;
		if (!strLQWF.equals("SFC")) {

			listAdapter = new DelButtonAdapter(this, list, R.layout.jdd_jclq_xhlb_item, new String[] {
					"buy_jcxhlb_list_mid", "buy_jcxhlb_list_hteam", "buy_jcxhlb_list_vteam", "buy_jcxhlb_list_sp",
					"buy_jcxhlb_list_delete", "list_strLQWF" }, new int[] { R.id.tv_item_vteam, R.id.tv_item_hteam,
					R.id.btn_item_s, R.id.buy_jcxhlb_list_p, R.id.btn_item_f, R.id.btn_jcxhlb_list_delete });

			currLen = listAdapter.GetFootList().size();
			if (currLen != len) {
				bs = 1;
				passType = "";
				allMoney = 0;
				selected = new boolean[] { false, false, false, false, false, false, false };

				et_beishu.setText("1");
				moneyText.setText("共0彩豆");
				btnChioce.setText("请选择过关方式");
				tvMyuce.setText("0");
			}
			if (currLen > 0) {
				list = new ArrayList<HashMap<String, Object>>();
				// 初始化全局JC变量
				ArrayList<ChildDTO> list_jcdto = new ArrayList<ChildDTO>();
				ApplicationData.getInstance().setList_jcdto(list_jcdto);

				for (ChildDTO jcdto : listAdapter.GetFootList()) {
					String jc_mid = jcdto.getmId();
					String str_team = jcdto.getStr_team();
					String str_hteam = jcdto.gethTeam();
					String str_vteam = jcdto.getvTeam();
					String str_sp = jcdto.getStr_sp();
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("buy_jcxhlb_list_mid", jc_mid);
					map.put("buy_jcxhlb_list_team", str_team);
					map.put("buy_jcxhlb_list_hteam", str_hteam);
					map.put("buy_jcxhlb_list_vteam", str_vteam);
					map.put("buy_jcxhlb_list_sp", str_sp);
					map.put("buy_jcxhlb_list_delete", R.color.common_del);
					map.put("list_strLQWF", strLQWF);
					list.add(map);
					ApplicationData.getInstance().getList_jcdto().add(jcdto);
				}
			} else {
				buy_jczqxhlb_linearlayout01.setVisibility(View.GONE);
				buy_jczqxhlb_linearlayout02.setVisibility(View.VISIBLE);
			}
			List<ChildDTO> studentList = new ArrayList<ChildDTO>();
			studentList = ApplicationData.getInstance().getList_jcdto();
			tipText.setText("共" + studentList.size() + "场比赛，截止时间：" + studentList.get(0).geteTime());
			listView.setAdapter(listAdapter);
		} else {// 胜分差
			listAdapterBQC = new DelButtonAdapterJCZQBQC(this, list, R.layout.buy_jczqbqcxhlb_list, new String[] {
					"buy_jcxhlb_list_mid", "buy_jcxhlb_list_hteam", "buy_jcxhlb_list_vteam", "buy_jcxhlb_list_touzhu",
					"buy_jcxhlb_list_delete", "buy_jcxhlb_list_sp" }, //
					new int[] { R.id.buy_jcxhlb_list_vteam, R.id.buy_jcxhlb_list_hteam, R.id.buy_jcxhlb_list_touzhu,
							R.id.buy_jcxhlb_list_delete }, strLQWF);

			currLen = listAdapterBQC.GetFootList().size();
			if (currLen != len) {
				bs = 1;
				passType = "";
				allMoney = 0;
				selected = new boolean[] { false, false, false, false, false, false, false };
				bfselected = new boolean[] { false, false, false, false };
				et_beishu.setText("1");
				moneyText.setText("共0彩豆");
				btnChioce.setText("请选择过关方式");
				tvMyuce.setText("0");
			}
			if (currLen > 0) {
				list = new ArrayList<HashMap<String, Object>>();
				// 初始化全局JC变量
				ArrayList<ChildDTO> list_jcdto = new ArrayList<ChildDTO>();
				ApplicationData.getInstance().setList_jcdto(list_jcdto);

				for (ChildDTO jcdto : listAdapterBQC.GetFootList()) {
					String jc_mid = jcdto.getmId();
					String str_team = jcdto.getStr_team();
					String str_hteam = jcdto.gethTeam();
					String str_vteam = jcdto.getvTeam();
					String str_touzhu = jcdto.getBtnsfcAllcontent();
					String str_sp = jcdto.getBqc_selectsp();
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("buy_jcxhlb_list_mid", jc_mid);
					map.put("buy_jcxhlb_list_team", str_team);
					map.put("buy_jcxhlb_list_hteam", str_hteam);
					map.put("buy_jcxhlb_list_vteam", str_vteam);
					map.put("buy_jcxhlb_list_touzhu", str_touzhu);
					map.put("buy_jcxhlb_list_sp", str_sp);// sp
					map.put("buy_jcxhlb_list_delete", R.color.common_del);
					list.add(map);
					ApplicationData.getInstance().getList_jcdto().add(jcdto);
				}
			} else {
				buy_jczqxhlb_linearlayout01.setVisibility(View.GONE);
				buy_jczqxhlb_linearlayout02.setVisibility(View.VISIBLE);
			}
			List<ChildDTO> studentList = new ArrayList<ChildDTO>();
			studentList = ApplicationData.getInstance().getList_jcdto();
			tipText.setText("共" + studentList.size() + "场比赛，截止时间：" + studentList.get(0).geteTime());
			listView.setAdapter(listAdapterBQC);
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == REQ_CODE_BUYMAIN || requestCode == REQ_CODE_NO_MONEY_2_RECHARGE) {
				ApplicationData.getInstance().resetJCData();
				setResult(110);
				finish();
			}
		}
	};

	// titleBar标题栏
	public void titleBar() {
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setBackgroundResource(R.drawable.top_title_back_bg);
		;
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (currLen <= 0) {
					// 获得自定义的应用程序BallDTO,初始化
					ApplicationData.getInstance().resetJCData();
					initMoney();
					setResult(RESULT_CANCELED);
					JcBasketballxhlbActivity.this.finish();
				} else {
					MyDialog.Builder dialog = new MyDialog.Builder(JcBasketballxhlbActivity.this);
					dialog.setTitle("退出提示");
					dialog.setMessage("退出后您的投注将不会保存，确认继续?");
					dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 获得自定义的应用程序BallDTO,初始化
							ApplicationData.getInstance().resetJCData();
							initMoney();
							setResult(RESULT_CANCELED);
							dialog.cancel();
							JcBasketballxhlbActivity.this.finish();
						}
					});
					dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					}).create().show();

				}
			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_play_method);
		String title = "-";
		if (strLQWF.equals("RFSF")) {
			title = "竞彩篮球（让分胜负）";
		} else if (strLQWF.equals("SF")) {
			title = "竞彩篮球（胜负）";
		} else if (strLQWF.equals("SFC")) {
			title = "竞彩篮球（胜分差）";
		} else if (strLQWF.equals("DXF")) {
			title = "竞彩篮球（大小分）";
		}
		info.setText(title);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (currLen <= 0) {
				ApplicationData.getInstance().resetJCData();
				initMoney();
				setResult(RESULT_OK);
				JcBasketballxhlbActivity.this.finish();
			} else {
				MyDialog.Builder dialog = new MyDialog.Builder(JcBasketballxhlbActivity.this);
				dialog.setTitle("退出提示");
				dialog.setMessage("退出后您的投注将不会保存，确认继续?");
				dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 获得自定义的应用程序BallDTO,初始化
						ApplicationData.getInstance().resetJCData();
						initMoney();
						setResult(RESULT_OK);
						dialog.cancel();
						JcBasketballxhlbActivity.this.finish();
					}
				});
				dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).create().show();
			}
		} else {
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	};
}
